import store, { STORE_KEY } from '@store'
import router, { initRoutes } from './../router'

import $cache from './cache'
import $common, { trans } from './common'
import $service from './../services'
import { ElMessageBox } from 'element-plus'

export { default as date } from './date'
export { default as valid } from './valid'
export { default as event } from './event'

export const cache = $cache
export const common = $common
export const service = $service

export const initDynamicRoutes = async (callback) => {
    // if (!store.state.business.token || store.state.app.mainRoutes) {
    //     callback && callback()
    //     return true
    // }
    const res = $cache.get($cache.key.ROUTERS)
    //如果有那么先用，后更新路由
    if (res) {
        initRoutes(res)
    } else {
        // res = await $service.system.routes()
        // if (!res) {
        //     callback && callback()
        //     return true
        // }
    }
    if (store.state.business.token) {
        // service.user.routers()
        // service.user.info()
    }
    callback && callback()
    return true
}

export const init = async () => {
    router.beforeEach((to, from, next) => {
        if (to.path !== '/login') {
            initToken()
            if (!store.state.business.token) {
                $common.toLogin()
            } else {
                initData()
                next()
            }
        } else {
            initData()
            next()
        }
    })

    if (typeof String.prototype.trim === 'undefined') {
        String.prototype.trim = function () {
            return String(this).replace(/^\s+|\s+$/g, '')
        }
    }
}

/**
 * 此处如果没有放入store中，放入
 * @returns
 */
const initToken = () => {
    if (store.state.business.token) return
    let token = $cache.get($cache.key.ACCESS_TOKEN)
    if (token) {
        store.commit(STORE_KEY.M_UPDATE_TOKEN, token)
    }
}
/**
 *
 * @returns 此处拿取全局数据，放入store，有的话就不拿
 */
const initData = () => {
    if (!store.state.business.token) return
}

export const confirm = async (
    message,
    title,
    confirmButtonText = '确定',
    cancelButtonText = '取消'
) => {
    const res = await trans(
        ElMessageBox.confirm(message, title || '提示', {
            confirmButtonText,
            cancelButtonText,
            showClose: false,
            closeOnClickModal: false,
            type: 'warning'
        })
    )
    if (res === 'confirm') {
        return true
    }
    return false
}
